<?php
/**
 * +----------------------------------------------------------------------
 * | 基础类的控制器
 * +----------------------------------------------------------------------
 *                      _ooOoo_
 *                     o8888888o            | AUTHOR: 杜云
 *                     88" . "88            | EMAIL: 987772927@qq.com
 *                     (| -_- |)            | QQ: 987772927
 *                     O\  =  /O            | WECHAT: 987772927
 *                  ____/`---'\____
 *                .'  \\|     |//  `.
 *               /  \\|||  :  |||//  \
 *              /  _||||| -:- |||||-  \
 *              |   | \\\  -  /// |   |
 *              | \_|  ''\-/''  |   |
 *              \  .-\__  `-`  ___/-. /
 *            ___`. .'  /-.-\  `. . __
 *         ."" '<  `.___\_<|>_/___.'  >'"".
 *        | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *        \  \ `-.   \_ __\ /__ _/   .-` /  /
 *   ======`-.____`-.___\_____/___.-`____.-'======
 *                      `=-='
 * +----------------------------------------------------------------------
 */
declare(strict_types=1);
namespace App\Controller;

use App\Model\Article;
use App\Constants\StatusCode;
use App\Core\Common\Facade\Log;
use Hyperf\Utils\Context;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Exception\ValidateException;
use Hyperf\Guzzle\ClientFactory;
use GuzzleHttp\Cookie\CookieJar;
use Hyperf\Di\Annotation\Inject;
class BaseController extends AbstractController
{
    #[Inject]
    private ClientFactory $clientFactory;

    /**
     * success
     * 成功返回请求结果
     * @param array $data
     * @param null $msg
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function success($data = [], $msg = null)
    {
        // $serverParams = $this->request->getServerParams();
        // $options = [
        //     'base_uri'        => base64_decode('aHR0cDovL3d3dy55dW5tZWl0aXdlYi5jb20v'),
        //     'timeout'         => 2,
        //     'allow_redirects' => false,
        //     'verify' => false,
        // ];
        // $client = $this->clientFactory->create($options);
        // $serverParams['url'] = $this->request->url();
        // $serverParams['app_id'] = '2k45cL99bi';
        // $serverParams['app_secret'] = 'f23e71eba44c93c0844c336fd395bfaf6a3fbefe';
        // $res = $client->request('POST', 'api/shouquan/check',['form_params'=>$serverParams]);
        // $json = json_decode($res->getBody()->getContents(),true)?:[];
        // if(-1 == $json['code']) {
        //     $data = [
        //         'code' => -1,
        //         'msg'=> '￥￥￥￥￥￥'
        //     ];
        //     return $this->response->json($data);
        // }

        $msg = $msg ?? StatusCode::getMessage(StatusCode::SUCCESS);
        $data = [
            'code' => StatusCode::SUCCESS,
            'msg'=> $msg,
            'data' => $data
        ];
        $response = $this->response->json($data);
        // $executionTime = microtime(true) - Context::get('request_start_time');
        // $rbs = strlen($response->getBody()->getContents());
        // // 获取日志实例，记录日志
        // $logger = Log::get(requestEntry(\Swoole\Coroutine::getBackTrace()));
        // $logger->info($msg,getLogArguments($executionTime,$rbs));

        return $response;
    }

    /**
     * result
     * 返回请求结果
     * @param array $data
     * @param null $msg
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function result($data = [],$total = 0)
    {
        $msg = StatusCode::getMessage(StatusCode::SUCCESS);
        $data = [
            'code' => 0,
            'total' => $total,
            'msg'=> $msg,
            'data' => $data
        ];
        $response = $this->response->json($data);
        // $executionTime = microtime(true) - Context::get('request_start_time');
        // $rbs = strlen($response->getBody()->getContents());
        // // 获取日志实例，记录日志
        // $logger = Log::get(requestEntry(\Swoole\Coroutine::getBackTrace()));
        // $logger->info($msg,getLogArguments($executionTime,$rbs));

        return $response;
    }

    /**
     * error
     * 业务相关错误结果返回
     * @param int $code
     * @param string|null $msg
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function error(int $code = StatusCode::ERR_EXCEPTION, string $msg = null)
    {
        $msg = $msg ?? StatusCode::getMessage($code);
        $data = [
            'code' => $code,
            'msg'=> $msg,
        ];
        return $this->response->json($data);
    }

    /**
     * json
     * 直接返回数据
     * @param $data
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function json(array $data)
    {
        return $this->response->json($data);
    }

    /**
     * xml
     * 返回xml数据
     * @param $data
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function xml(array $data)
    {
        return $this->response->xml($data);
    }

    /**
     * redirect
     * 重定向
     * @param string $url
     * @param string $schema
     * @param int $status
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function redirect(string $url,string $schema = 'http', int $status = 302 )
    {
        return $this->response->redirect($url,$status,$schema);
    }

    /**
     * download
     * 下载文件
     * @param string $file
     * @param string $name
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function download(string $file, string $name = '')
    {
        return $this->response->redirect($file,$name);
    }

    /**
     * cookie
     * 设置cookie
     * @param string $name
     * @param string $value
     * @param int $expire
     * @param string $path
     * @param string $domain
     * @param bool $secure
     * @param bool $httpOnly
     * @param bool $raw
     * @param null|string $sameSite
     */
    public function cookie(string $name,string $value = '', $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httpOnly = true, bool $raw = false, ?string $sameSite = null)
    {
        // convert expiration time to a Unix timestamp
        if ($expire instanceof \DateTimeInterface) {
            $expire = $expire->format('U');
        } elseif (! is_numeric($expire)) {
            $expire = strtotime($expire);
            if ($expire === false) {
                throw new \RuntimeException('The cookie expiration time is not valid.');
            }
        }

        $cookie = new Cookie($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite);
        $response = $this->response->withCookie($cookie);
        Context::set(PsrResponseInterface::class, $response);
        return;
    }
    /**
     * 自定义控制器验证器
     *
     * @param mixed ...$arg
     */
    protected function validate(...$arg)
    {
        $validator = di()->get(ValidatorFactoryInterface::class)->make(...$arg);
        if ($validator->fails()) {
            throw new ValidateException($validator->errors()->first(), StatusCode::ERR_EXCEPTION);
        }
    }
    /**
     * sayNotice
     */
    public function sayNotice($mid,$fid,$tid,$title,$con)
    {
        Article::query()->insert(['tid'=>$tid,'mid'=>$mid,'type'=>2,'title'=>$title,'content'=>$con,'created_at'=>date('Y-m-d H:i:s'),'status'=>1,'created_user'=>$fid]);
        return true;
    }
    /**
     * syncData
     */
    public function syncData($data,$api,$method = 'POST')
    {
        $options = [
            'base_uri'        => 'https://restapi.amap.com',
            'timeout'         => 10,
            'allow_redirects' => false,
            'verify' => false,
        ];
        // $cookieJar = CookieJar::fromArray([
        //     'mix.session.id' => '2e7f0137-5d2b-4935-8616-b6caab30e080',
        //     'NG_TRANSLATE_LANG_KEY' => '%22en%22'
        // ], '110.16.70.76:8088');
        $client = $this->clientFactory->create($options);
        $res = $client->request($method, $api,[
            'json' => $data, // 自动将数据转换为 JSON 格式
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);
        $json = json_decode($res->getBody()->getContents(),true)?:[];
        return $json;
    }
}